package com.fenghongzhang.lib_xmpp;

import android.util.Log;

import com.fenghongzhang.lib_xmpp.contract.IXmppConfig;
import com.fenghongzhang.lib_xmpp.contract.IXmppUser;
import com.fenghongzhang.lib_xmpp.impl.DefaultXmppConfigImpl;
import com.fenghongzhang.lib_xmpp.impl.DefaultXmppUserImpl;
import com.orhanobut.logger.Logger;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.stringprep.XmppStringprepException;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class XmppManager {
    private final String TAG=XmppManager.class.getSimpleName();
    /**
     * Xmpp 配置信息
     */
    private IXmppConfig xmppConfig;
    /**
     * 获取连接
     * @return
     */
    public AbstractXMPPConnection getConnection(){
        return this.mConnection;
    }

    /**
     * 用户管理
     */
    private IXmppUser xmppUserManager;
    /**
     * Xmpp Connection
     */
    private AbstractXMPPConnection mConnection;

    private volatile static XmppManager instance=null;
    private XmppManager(){
        //连接IM服务器
        connect();

    }
    public static XmppManager getInstance(){
        if (instance==null){
            synchronized (XmppManager.class){
                if (instance==null){
                    instance=new XmppManager();
                }
            }
        }
        return instance;
    }

    /**
     * 连接Xmpp服务器
     */
    private void connect(){
        try {
            XMPPTCPConnectionConfiguration configuration=XMPPTCPConnectionConfiguration.builder()
                    .setXmppDomain(getXmppConfig().getDomainName())
                    .setHostAddress(InetAddress.getByName(getXmppConfig().getHostAddress()))
                    .setPort(getXmppConfig().getPort())
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                    .setCompressionEnabled(false)
                    .setDebuggerEnabled(true)
                    //.setSendPresence(false)//设置离线状态获取离线消息
                    .build();

            //设置需要经过同意才可以加为好友
            Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
            AbstractXMPPConnection connection = new XMPPTCPConnection(configuration);

            connection.connect();// 连接, 可设置监听
            connection.addConnectionListener(new XMPPConnectionListener());
            this.mConnection = connection;


        } catch (XmppStringprepException e) {
            Logger.e(e.getMessage());
        } catch (UnknownHostException e) {
            Logger.e(e.getMessage());
        } catch (InterruptedException e) {
            Logger.e(e.getMessage());
        } catch (IOException e) {
            Logger.e(e.getMessage());
        } catch (SmackException e) {
            Logger.e(e.getMessage());
        } catch (XMPPException e) {
            Logger.e(e.getMessage());
        }
    }

    /**
     * 获取用户管理对象
     * @return
     */
    public IXmppUser getXmppUserManager(){
        if (null==xmppUserManager){
            xmppUserManager=new DefaultXmppUserImpl();
        }
        return xmppUserManager;
    }

    /**
     * 获取XmppConfig
     * @return
     */
    public IXmppConfig getXmppConfig(){
        if (null==xmppConfig){
            xmppConfig=new DefaultXmppConfigImpl();
        }
        return xmppConfig;
    }
    /**
     * 添加好友变化监听
     */
    public XmppManager addRosterListener(){
      //  addFriendListener();
        return this;
    }

    /**
     * 服务器连接监听
     */
    private class XMPPConnectionListener implements ConnectionListener {
        @Override
        public void connected(XMPPConnection connection) {
            Logger.d("connected: ");
        }

        @Override
        public void authenticated(XMPPConnection connection, boolean resumed) {
            Logger.d("authenticated: ");
            addRosterListener();
            //开启心跳处理
            //startHeartDump();
            Logger.i("start heartdump...");
        }

        @Override
        public void connectionClosed() {
            Logger.d( "connectionClosed: ");
            //开启心跳处理
            //startHeartDump();
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            Logger.d("connectionClosedOnError: ");
            //开启心跳处理
            //startHeartDump();
        }

        @Override
        public void reconnectionSuccessful() {
            Logger.d("reconnectionSuccessful: ");
        }

        @Override
        public void reconnectingIn(int seconds) {
            Logger.d( "reconnectingIn: ");
        }

        @Override
        public void reconnectionFailed(Exception e) {
            Logger.d("reconnectionFailed: ");
        }
    }

}
